import jwt from 'jsonwebtoken'
import { asyncTasks } from 'roc-utils'
import db from '../app/database.js'
import api from '../utils/apiBase.js'
import { md5 } from '../utils/crypto-utils.js'
import { PRIVATE_KEY } from '../app/config.js'
import redisClient from '../app/redis.js'

class LoginService {
    /**
     * 用户登录
     * @param {string} username
     * @param {string} password
     * @param {string} uuid
     * @param {string} captcha
     * @returns {Promise<{code: number, data: *, message: string}|{code: number, data: string, message: string}|void>}
     */
    async login(username, password, uuid, captcha) {
        if (!uuid) {
            return api.error('uuid为空!')
        }
        const redisCaptcha = await redisClient.get(uuid)
        if (!username) {
            return api.error('用户名为空!')
        } else if (!password) {
            return api.error('密码为空!')
        } else if (!captcha) {
            return api.error('验证码为空!')
        } else if (redisCaptcha !== captcha) {
            return api.error('验证码错误!', 2)
        }
        const sql = 'SELECT * FROM roc_user WHERE username = ?'
        const [err, results] = await asyncTasks(db.query(sql, [username]))
        if (err) return console.log('sql错误:', err.sqlMessage)
        const users = results[0]
        if (users.length === 0) {
            return api.error('无此用户')
        } else if (md5(password) !== users[0].password) {
            return api.error('密码错误')
        } else {
            /*
        sign(数据体, 私钥, 选项{algorithm: 算法, expiresIn: 到期时间})
        返回token
      */
            const token = jwt.sign(
                {
                    id: users[0].id,
                    username: users[0].username,
                },
                PRIVATE_KEY,
                {
                    algorithm: 'RS256',
                    expiresIn: 60 * 60 * 24,
                },
            )
            await redisClient.del(uuid)
            return api.success({ token })
        }
    }
}
export default new LoginService()
